#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

//网页
String myhtmlPage =
    String("") +
    "<html>" +
    "<head>" +
    "    <meta charset=\"utf-8\">" +
    "    <title>ESP8266 Web Server Test</title>" +
    "    <script defer=\"defer\">" +
    "        function ledSwitch() {" +
    "            var xmlhttp;" +
    //这一段必备是注册函数不同浏览器的兼容
    "            if (window.XMLHttpRequest) {" +
    "                xmlhttp = new XMLHttpRequest();" +
    "            } else {" +
    "                xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");}" +
    //
  
 // *这一段是按钮反馈可以不要
 /*
   "            xmlhttp.onreadystatechange = function () {" +
    "                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {" +
    "                    document.getElementById(\"txtState\").innerHTML = xmlhttp.responseText;" +
    "                }" +
    "            }," +*/
    "            xmlhttp.open(\"GET\", \"Switch\", true);" +
    "            xmlhttp.send(); " +
    "        }" +
    "    </script>" +
    "</head>" +
    "<body>" +
    "    <div id=\"txtState\">Unkwon</div>" +
    "    <input type=\"button\" value=\"Switch\" onclick=\"ledSwitch()\">" +
    "</body>" +
    "</html>";

//u8 button_state ;

const char* ssid = "fish";
const char* password = "12345679";

ESP8266WebServer server(80);

void handleRoot() {
  server.send(200, "text/html", myhtmlPage); //！！！注意返回网页需要用"text/html" ！！！
}
/*处理函数*/
void handleSwitch() {
    Serial.println("onclick");                    
}

void handleNotFound() {
  server.send(404, "text/plain", "404");
}
void setup() {
  // put your setup code here, to run once:
    //初始化LED
  pinMode(2, OUTPUT);
  digitalWrite(2, HIGH);
  pinMode(0,INPUT);

  //初始化串口
  Serial.begin(9600);
  //初始化网络
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(WiFi.localIP());

  //初始化WebServer
  server.on("/", handleRoot);
  server.on("/Switch", handleSwitch);
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  if(digitalRead(0)== 0)
  {
    Serial.println(WiFi.localIP());           // NodeMCU的IP地址
    while (digitalRead(0)== 0){}
  }
    server.handleClient();
}
